<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 15/10/19
 * Time: 下午3:04
 */
class SceUserController extends BaseController {
    /*
     * 技师登陆
     * */
    public function login(){
        $validator = Validator::make(Input::all(),
            array(
                'account' => 'required',
                'passwd' => 'required',
                'imei' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $account = Input::get('account');
            $passwd = md5(Input::get('passwd'));
            $imei = Input::get('imei');
            //验证密码
            $engineer = MaintenanceEngineers::where('account',$account)
                ->where('passwd',$passwd)
                ->where('status',1)
                ->where('type','shop')
                ->select(array('id','name','title','skill_level','type','type_id','pwd_at'))
                ->first();
            if(!is_null($engineer)){
                $pad = MaintenancePads::where('imei',$imei)
                    ->where('status',1)
                    ->select(array('id','name','shop_id','work_station_num'))
                    ->first();

                if(is_null($pad)){
                    Log::error("error", array("system" => "sce" ,"event" => "login", 'input' =>Input::all() ));
                    $response = Lang::get("sce_error.login_pad_not_bind_workstation");
                    break;
                }
                if($engineer->type_id != $pad->shop_id){
                    $response = Lang::get("sce_error.shop_not_match_1018");
                    break;
                }
                
                $ms=MaintenanceShops::find($engineer->type_id);

                if (strtotime($engineer->pwd_at) + $ms->password_day*24*60*60 <= time()) {  //当前时间是不是超过了门店用户的有效登陆时间
                    $response = Lang::get("sce_error.sce_user_login_error_1023");
                    break;
                }
                
                $ma_station=MaintenanceStation::find($pad->work_station_num);
                //记录技师token，到数据库
                try {
                    EngineerTokens::where('engineer_id',$engineer->id)->delete();
                    EngineerTokens::where('work_station_num',$pad->work_station_num)->delete();//删除该工位其他技师的登录信息
                    $engineer_token = new EngineerTokens;
                    $engineer_token->engineer_id = $engineer->id;
                    $engineer_token->token = md5($account.time().rand(0,100));
                    $engineer_token->work_station_num = $pad->work_station_num;
                    $engineer_token->created_at = Common::num2DateTime(time());
                    $engineer_token->out_time_at = Common::num2DateTime(time() + Config::get("engineer.token_time_out"));
                    $engineer_token->save();

                    //记录登录信息 暂时只更新登录时间
                    $m=MaintenanceEngineers::find($engineer->id);
                    $m->last_login_at=Common::num2DateTime(time());
                    $m->save();
                } catch (Exception $e) {
                    Log::error("error", array("system" => "sce" ,"event" => "login", 'input' =>Input::all() ,"exception" => $e));
                    $response = Lang::get("sce_error.login_create_token_error_1003");
                    break;
                }

                $shop = MaintenanceShops::where('id',$pad->shop_id)
                    ->select(array('name','city_id'))
                    ->first();
                $city = ResourceCityType::select("short_name")->where('id',$shop->city_id)->first();
                $city_short_name = !empty($city) ? $city->short_name : "";
            }else{
                $response = Lang::get("sce_error.login_not_exist_error_1002");
                break;
            }

            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'token' => $engineer_token->token,
                    'expired' => $engineer_token->out_time_at,
                    'shop' => array(
                        'shop_id' => $pad->shop_id,
                        'shop_name' => $shop->name,
                        'city_short_name' =>$city_short_name,
                    ),
                    'device' => array(
                        'device_id' => $pad->id,
                        'device_name' => $pad->name,
                        'work_station_num' => $pad->work_station_num,
                        'work_name' =>isset($ma_station->name)?$ma_station->name:""
                    ),
                    'engineer' => array(
                        'id' => $engineer->id,
                        'name' => $engineer->name,
                        'title' => $engineer->title,
                        'sidkill_level' => $engineer->skill_level,
                    ),
                )
            );

        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "login", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 技师登出
     * */
    public function logout(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){

                break;
            }
            try{
                EngineerTokens::where('engineer_id',$engineer_data->id)->delete();
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "logout", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.user_token_clean_error_1005");
                break;
            }

            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'id' => $engineer_data->id
                )
            );

        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "logout", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 技师端门店信息
     * */
    public function imeiInfo(){
        $validator = Validator::make(Input::all(),
            array(
                'imei' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        $imei = Input::get('imei');
        
        do {
            $pad = MaintenancePads::where('imei',$imei)
                ->where('status',1)
                ->select(array('id','name','shop_id','work_station_num'))
                ->first();
            if(is_null($pad)){
                Log::error("error", array("system" => "sce" ,"event" => "login", 'input' =>Input::all() ));
                $response = Lang::get("sce_error.login_pad_not_bind_workstation");
                break;
            }
            
            $shop = MaintenanceShops::where('id',$pad->shop_id)
                ->select(array('name','id'))
                ->first();
            if (is_null($shop)) {
                $name = "无所属门店";
                $shop_id = 0;
            }else {
                $name = $shop->name;
                $shop_id = $shop->id;
            }
            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'name' => $name,
                    'shop_id' => $shop_id,
                )
            );

        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "logout", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    
    
    /*
     * 更新技师信息
     * */
    public function update(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'name' => 'required',
//                'passwd' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $name = Input::get('name');
//            $passwd = md5(Input::get('passwd'));

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                $response = Lang::get("sce_error.user_token_not_exist_1004");
                break;
            }

            try{
                MaintenanceEngineers::where('id',$engineer_data->id)
                    ->update(array(
                        'name' => $name,
//                        'passwd' => $passwd
                    ));
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "update", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.user_info_update_error_1006");
                break;
            }

            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'name' => $name,
                    'title' => $engineer_data->title,
                    'skill_level' => $engineer_data->skill_level,
                    'type' => $engineer_data->type,
                    'type_id' => $engineer_data->type_id,
                )
            );

        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "update", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /*
     * 更新技师信息
     * */
    public function updatePwd(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'passwd' => 'required',
                'old_passwd' => 'required'
            )
        );
    
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }
    
            //传入参数
            $token = Input::get('token');
            $passwd = md5(Input::get('passwd'));
            $old_passwd = md5(Input::get('old_passwd'));
    
            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                $response = Lang::get("sce_error.user_token_not_exist_1004");
                break;
            }
            if($engineer_data->passwd != $old_passwd  && $engineer_data->passwd != strtoupper($old_passwd) ){
                $response = Lang::get("sce_error.passwd_error_1020");
                break;
            }
    
            try{
                MaintenanceEngineers::where('id',$engineer_data->id)
                ->update(array(
                'passwd' => $passwd,
                'pwd_at' => date("Y-m-d H:i:s")
                ));
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "update", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.user_info_update_error_1006");
                break;
            }
            
            try{
                EngineerTokens::where('engineer_id',$engineer_data->id)->delete();
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "logout", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.user_token_clean_error_1005");
                break;
            }
    
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "updatePwd", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 更新技师信息
     * */
    public function updatePwd2(){
        $validator = Validator::make(Input::all(),
            array(
                'account' => 'required',
                'passwd' => 'required',
                'old_passwd' => 'required'
            )
        );
    
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }
    
            //传入参数
            $account = Input::get('account');
            $passwd = strtoupper(md5(Input::get('passwd')));
            $old_passwd = strtoupper(md5(Input::get('old_passwd')));
            //验证密码
            $engineer = MaintenanceEngineers::where('account',$account)
                ->where('passwd',$old_passwd)
                ->where('status',1)
                ->where('type','shop')
                ->select(array('id','name','title','skill_level','type','type_id'))
                ->first();
            if (is_null($engineer)) {
                $response = Lang::get("sce_error.login_not_exist_error_1002");
                break;
            }
            
            try{
                MaintenanceEngineers::where('id',$engineer->id)
                ->update(array(
                'passwd' => $passwd,
                'pwd_at' => date("Y-m-d H:i:s")
                ));
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "update", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.user_info_update_error_1006");
                break;
            }
            
            try{
                EngineerTokens::where('engineer_id',$engineer->id)->delete();
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "logout", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.user_token_clean_error_1005");
                break;
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("user_id" =>$engineer->id));
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "updatePwd", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /*
     * 技师登陆
     * */
    public function managerLogin(){
        $validator = Validator::make(Input::all(),
            array(
                'account' => 'required',
                'passwd' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }
    
            //传入参数
            $account = Input::get('account');
            $passwd = md5(Input::get('passwd'));
    
            //验证密码
            $engineer = MaintenanceEngineers::where('account',$account)
            ->where('passwd',$passwd)
            ->where('status',1)
            ->where('type','shop')
            ->select(array('id','name','title','skill_level','type','type_id'))
            ->first();
            if(!is_null($engineer)){
    
                //记录技师token，到数据库
                try {
                    EngineerTokens::where('engineer_id',$engineer->id)->delete();
                    $engineer_token = new EngineerTokens;
                    $engineer_token->engineer_id = $engineer->id;
                    $engineer_token->token = md5($account.time().rand(0,100));
                    $engineer_token->work_station_num = 0;
                    $engineer_token->created_at = Common::num2DateTime(time());
                    $engineer_token->out_time_at = Common::num2DateTime(time() + Config::get("engineer.token_time_out"));
                    $engineer_token->save();
    
                    //记录登录信息 暂时只更新登录时间
                    $m=MaintenanceEngineers::find($engineer->id);
                    $m->last_login_at=Common::num2DateTime(time());
                    $m->save();
                } catch (Exception $e) {
                    Log::error("error", array("system" => "sce" ,"event" => "login", 'input' =>Input::all() ,"exception" => $e));
                    $response = Lang::get("sce_error.login_create_token_error_1003");
                    break;
                }
    
                $shop = MaintenanceShops::where('id',$engineer->type_id)
                ->select(array('name'))
                ->first();
            }else{
                $response = Lang::get("sce_error.login_not_exist_error_1002");
                break;
            }
    
            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'token' => $engineer_token->token,
                    'expired' => $engineer_token->out_time_at,
                    'shop' => array(
                        'shop_id' => $engineer->type_id,
                        'shop_name' => $shop->name
                    ),
                    'engineer' => array(
                        'id' => $engineer->id,
                        'name' => $engineer->name,
                        'title' => $engineer->title,
                        'sidkill_level' => $engineer->skill_level,
                    ),
                )
            );
    
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "login", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}